/**
 * @Description: 加载提示类(单例模式)
 * @author Beon
 * @date 2021/1/4
*/
import * as ora from 'ora';
import {ClassTool} from './classTool';

export class OraLoading{
    @ClassTool.newSelf
    static oraLoading: OraLoading

    protected loading: ora.Ora
    private _value: string
    private message: string|symbol
    private Symbol = Symbol()

    constructor() {
        this._value = '';
        this.loading = ora();
        process.on('exit', this.runError.bind(this));
    }

    /**
     * 构造加载器对象
     * @param {*} Target 构造对象
     * @param {String} propertyKey key值
     */
    // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
    static beProxy<T>(Target: T, propertyKey: string): void {
        Target[propertyKey] = OraLoading.oraLoading;
    }

    /**
     * 执行出错回调
     * @param {Number} error 错误条数
     */
    private runError(error: number): void {
        if (error && this._value) {
            this.loading.fail(this._value + '出错\n');
        }
    }

    set value(value: string|symbol) {
        if (value === this.Symbol) {
            this.loading.succeed(this._value + '进行中\n');
        } else {
            if (this._value && this._value !== value) {
                this.loading.succeed(this._value + '结束\n');
            }
            if (value){
                this.loading.start(value as string + '进行中\n');
            }
            this._value = value as string;
        }
    }

    get value(): string|symbol {
        return this._value;
    }

    /**
     * 停止加载信息
     */
    oraLoadingStop(): void {
        this.message = this.value;

        this.value = this.Symbol;
    }

    /**
     * 继续加载信息
     */
    oraLoadingStart(): void {
        this.value = this.message;
    }
}
